package official_account

import (
	"code.gitea.io/gitea/modules/setting"
	wechat_service_vo "code.gitea.io/gitea/services/wechat/vo"
	"context"
	"encoding/base64"
	binaryUtils "encoding/binary"
	"github.com/google/uuid"
	"strings"
	"time"
)

// GenerateTempQR 生成微信公众号临时二维码
func GenerateTempQR(
	ctx context.Context,
	sceneStr string, qrExpireSeconds int,
) (*wechat_service_vo.GenerateWechatOfficialAccountTempQRVO, error) {

	// 1. 检查参数 qrExpireSecondsOverride 和 sceneStrOverride: 若用户未指定，则从配置文件 app.ini 读取
	if qrExpireSeconds <= 0 {
		qrExpireSeconds = setting.Wechat.OfficialAccount.TempQrExpireSeconds
	}
	if len(sceneStr) == 0 {
		// 生成随机 sceneStr 场景值
		//  sceneStr生成规则：UUIDv4后边拼接 当前UnixNano时间戳转为byte数组后的Base64
		//  e.g, sceneStr == "1c78e8d914fb4307a3588ac0f6bc092a@yPXAm+ve5hc="
		bytesArrayUnit64 := make([]byte, 8)
		binaryUtils.LittleEndian.PutUint64(bytesArrayUnit64, uint64(time.Now().UnixNano()))
		currentTimestampNanoBase64 := base64.StdEncoding.EncodeToString(bytesArrayUnit64)
		sceneStr = strings.ReplaceAll(uuid.New().String(), "-", "") + "@" + currentTimestampNanoBase64
	}

	// 2. 调用 PowerWechat 生成微信公众号临时二维码
	qrData, err := setting.Wechat.OfficialAccount.PowerWechat.QRCode.Temporary(ctx, sceneStr, qrExpireSeconds)
	if err != nil {
		return nil, err
	}

	// 3. 封装 VO 返回
	wechatQrVo := &wechat_service_vo.GenerateWechatOfficialAccountTempQRVO{
		Ticket:        qrData.Ticket,
		ExpireSeconds: qrData.ExpireSeconds,
		Url:           qrData.Url,
		QrImageSrcUrl: "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + qrData.Ticket,
	}
	return wechatQrVo, nil
}
